// 添加和编辑 专题弹窗
import React, { Component } from 'react'
import { Button,Form, Input, Modal, Select,Upload ,Icon ,message,Transfer,Checkbox ,Spin } from 'antd'
const CheckboxGroup = Checkbox.Group;
import { connect } from 'react-redux'
import Ueditor from '../../components/Ueditor'
import Uploadimg from '../../components/uploadimg'
/* 引用接口文档路径 */
import {
  addSubject,editSubject,getReport
} from 'actions/materialManage'
const FormItem = Form.Item

@Form.create({
    mapPropsToFields(props) {
      return {
        name: Form.createFormField({
          ...props.content,
          value: props.content.name,
        }),
        coverPath: Form.createFormField({
          ...props.content,
          value: props.content.coverPath,
        }),
        introduction: Form.createFormField({
          ...props.content,
          value: props.content.introduction,
        }),
        searchKeywords: Form.createFormField({
          ...props.content,
          value: '',
        }),
      };
    } 
})

@connect(
  (state, props) => ({
    config: state.config,
    userInfoList: state.userInfoList,
  })
)


export default class ModalAddSubject extends Component {
  
    constructor (props) {
      super(props)
      this.state = {
        leftDataSource:[],
        rightTargetKeys:[],
        chooseId:[],//左侧选中的ID
        deleteId:[],//右侧选中的ID
        arryList:[],
        addImgUrl:"",
        subjectContent:"",//专题内容
        isSearch:false,
        isDelete:true,
        loading:false,
        imageflag:false,//图片裁剪框
      }
    }
    
    /*
      执行一次，在初始化render之前执行，如果在这个方法内调用setState，render()知道state发生变化，并且只执行一次
    */
    componentWillMount(){
      this.setState({
        addImgUrl: this.props.content.coverPath,
        subjectContent:this.props.content.content,
        rightTargetKeys:this.props.content.reportInfoList?this.props.content.reportInfoList:[],
        leftDataSource:[]
      })
    }
    

    searchReportList=()=>{
      this.props.form.validateFields(['searchKeywords'],(err, values)=>{
        if(!err){
          this.setState({isSearch:false})
          this.props.dispatch(getReport(
            {"title":values.searchKeywords},
            (respose) => {             
              this.setState({
                isSearch:true,
                leftDataSource:respose.respData.resultData
              })
            }))  
        }
      })
    }

    getChooseList(value){//左侧列表
      this.setState({chooseId:value})
    }

    chooseRight(value){//右侧列表
      this.setState({deleteId:value})
    }

    clearRightList(){//选中右侧的点击取消     
      let arryList2 = this.state.rightTargetKeys;
      for(var i = 0; i < this.state.deleteId.length;i++){
        for(var k = 0; k < arryList2.length;k++){
          if(arryList2[this.state.deleteId[i]].id == arryList2[k].id){
            arryList2.splice(k,1);
          }
        }
      }
      this.setState({
        isDelete:false
      })
      setTimeout(()=>{
        this.setState({
          isDelete:true
        })
      },1)
      this.setState({
        rightTargetKeys:arryList2,
        deleteId:[],
      })
    }

    setRightList(){//选中左边的点击确定
      let arryList = this.state.rightTargetKeys;
      for(var i = 0; i < this.state.chooseId.length;i++){
        arryList.push(this.state.leftDataSource[this.state.chooseId[i]])
      }
      arryList = this.uniqeByKeys(arryList,['id'])
      this.setState({
        rightTargetKeys:arryList,
      })
    }

    obj2key(obj,keys){
      var n = keys.length,
        key = [];
      while(n--){
        key.push(obj[keys[n]]);
      }
      return key.join('|');
    }

    uniqeByKeys(array,keys){ //数组对象深度去重
      var arr = [];
      var hash = {};
      for (var i = 0, j = array.length; i < j; i++) {
          var k = this.obj2key(array[i], keys);
          if (!(k in hash)) {
              hash[k] = true;
              arr .push(array[i]);
          }
      }
      return arr ;
    }
    imageuploaded() {
      this.setState({
        imageflag:true
      });
    }
    closeFn(){
      this.setState({
        imageflag:false
      });
    }
    urlFn(url){
      this.setState({
        imageflag:false,
        addImgUrl:url
      });
    }

    addReportSubmit(callback,e){//新增和编辑确定按钮
        e.preventDefault();
        this.props.form.validateFields(['name','introduction'],(err, values) => {
            if(!err){
                const ids  = []
                for(var i = 0; i<this.state.rightTargetKeys.length;i++ ){
                  ids.push(this.state.rightTargetKeys[i].id)
                }
                if(!this.state.addImgUrl){
                  message.error('请上传专题封面');
                  return;
                }
                if(ids.length == 0){
                  message.error('请选择关联报告');
                  return;
                }
                // if(UE.getEditor('content').getContent() == '' || UE.getEditor('content').getContent().length == 0){
                //   message.error('请输入专题简介');
                //   return;
                // }
                if(this.props.type == 1){
                  var datajson = {
                      "name":values.name,//专题名称
                      "coverPath":this.state.addImgUrl,//专题封面
                      "introduction":values.introduction,//专题简介
                      "content":UE.getEditor('content').getContent(),//专题内容
                      "reportIds":ids,//报告列表ID
                  }
                  //新增              
                  this.props.dispatch(addSubject(
                  datajson,
                  (respose) => {
                      callback&&callback()
                      message.success(respose.respMsg);
                      this.props.ModalCancel();
                  }))
                }else{
                    var datajson = {
                        "id":this.props.content.id,//大咖专题ID
                        "name":values.name,//专题名称
                        "coverPath":this.state.addImgUrl,//专题封面
                        "introduction":values.introduction,//专题简介
                        "content":UE.getEditor('content').getContent(),//专题内容
                        "reportIds":ids,//报告列表ID
                    }
                    //编辑
                    this.props.dispatch(editSubject(
                    datajson,
                    (respose) => {
                        callback&&callback()
                        message.success(respose.respMsg);
                        this.props.ModalCancel();
                    })) 
                }                                
            }
        });       
    }
    render () {
        const { getFieldDecorator } = this.props.form;
        const content = this.props.content;
        const uploadImg = {
            name: 'file',
            action: global.$GLOBALCONFIG.$ctx+'image/full/path/upload',
            headers: {
              authorization: 'holder ' + sessionStorage.getItem('token'),
            },
            data:{
                type:"2"
            },
            accept:"image/jpg,image/png,image/jpeg",
            beforeUpload: (file)=>{
              const isImg = file.type.substring(0,5) === 'image';
              if (!isImg) {
                message.error('请选择图片');
              }
              this.setState({
                loading:true
              })
              return isImg;
            },
            onChange:(info)=>{
              if (info.file.status !== 'uploading') {
                console.log('上传中')          
              }
              if (info.file.status === 'done') {
                console.log('上传完成')
                /* 把返回的路径赋值过去 */
                this.setState({
                    addImgUrl: info.file.response.respData,
                    loading:false
                })
              } else if (info.file.status === 'error') {
                message.error(info.file.response.respMsg);
              }
            },
            showUploadList:false,//不展示上传完成之后的文件列表
        }
        const formItemLayout = {
          labelCol: {
          //   xs: { span: 24},
            sm: { span: 3 },
          },
          wrapperCol: {
          //   xs: { span: 24 },
            sm: { span: 20 },
          },
        };
        return (
            <Modal
                width={"80%"}
                wrapClassName="vertical-center-modal"
                maskClosable={false}
                visible={this.props.ModalFlg}
                title={this.props.type == '1' ? "新增专题" : "编辑专题" }
                onCancel={this.props.ModalCancel}
                onOk={this.addReportSubmit.bind(this,this.props.callback)}
                destroyOnClose={true}
            >
            <div>
              <Form>
                <FormItem label="专题名称" {...formItemLayout}>
                  {
                    getFieldDecorator('name', {
                    rules: [{
                        required: true,message:"请输入专题名称"
                      }],
                    })(
                      <Input maxLength="20" placeholder="请输入关键字"   size="default" style={{ width: '180px' }} />
                    )
                  }              
                </FormItem>
                <FormItem label="专题封面" {...formItemLayout}>
                  <Spin spinning={this.state.loading} style={{width:"80px"}}>
                    <img onClick={this.imageuploaded.bind(this)} style={{width:"80px",verticalAlign:"bottom",marginRight:"10px"}} 
                        src={ this.state.addImgUrl ? this.state.addImgUrl :require('../../images/baseImg.png') }
                    />
                  </Spin>
                  {
                    this.state.imageflag?
                    <Uploadimg width={600} height={400} visible={this.state.imageflag} closeModal={this.closeFn.bind(this)} urlFn={this.urlFn.bind(this)}/>
                    :''
                  }
                </FormItem>
                <FormItem label="关联报告" {...formItemLayout}>
                  {
                    getFieldDecorator('searchKeywords', {
                    rules: [{
                        required: true,message:"请输入关键字"
                      }],
                    })(
                      <Input placeholder="请输入关键字" size="default" style={{ width: '200px' }} />
                    )
                  }  

                  <span style={{margin:"0 5px",cursor:"pointer"}} onClick={this.searchReportList}>搜索</span>    
                  
                </FormItem>
                <FormItem>
                  <div style={{width:'400px',height:'150px',marginLeft:'12%'}}>
                    {/* 左侧搜索结果 */}
                    <div style={{width:'180px',height:'150px',border:'1px solid #e8e8e8',float:'left',overflow:'auto',padding:'5px'}}>
                      { this.state.isSearch ?
                        <CheckboxGroup defaultValue={[]} onChange={this.getChooseList.bind(this)} >
                        {
                          this.state.leftDataSource.map((item,i)=> {
                            return(
                              <Checkbox value={i} key={i} >{item.title}</Checkbox>
                            )
                          })
                        }
                        </CheckboxGroup> : ''
                      }                     
                    </div>
                    {/* 操作 */}
                    <div style={{width:'30px',height:'150px',margin:'0 5px',float:'left'}}>
                        <span onClick={this.setRightList.bind(this)}>选择</span>
                        <span onClick={this.clearRightList.bind(this)}>取消</span>
                    </div>
                    {/* 右侧选中 */}
                    <div style={{width:'180px',height:'150px',border:'1px solid #e8e8e8',float:'left',overflow:'auto',padding:'5px'}}>
                      { this.state.isDelete ?
                        <CheckboxGroup  onChange={this.chooseRight.bind(this)} >
                        {
                          this.state.rightTargetKeys.map((item,i)=> {
                            return(
                              <Checkbox value={i} key={i} >{item.title}</Checkbox>
                            )
                          })
                        }
                        </CheckboxGroup> :''
                      }
                      
                    </div>
                  </div>
                </FormItem>
                <FormItem label="专题简介" {...formItemLayout}>
                  {
                    getFieldDecorator('introduction', {
                    rules: [{
                        required: true,message:"请输入专题简介"
                      }],
                    })(
                      <Input.TextArea  placeholder="请输入关键字"   size="default" style={{ width: '250px',height:'100px',resize:'none' }} />
                    )
                  }              
                </FormItem>
                <FormItem label="专题内容" {...formItemLayout}>
                  {/* 富文本 */}
                  <Ueditor  id="content" value={this.state.subjectContent} toolbars={2}  height="200" />
                </FormItem>
              </Form>
            </div>
          </Modal>
        )
    }
}